package com.diandireader.activity;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.widget.EditText;

public class DiandiReaderEditText extends EditText {
	private String text;
	private Context context;
	private float screenWidth,screenHeight;
	private int rowCharws,columnChars;
	private int x,y;
	public DiandiReaderEditText(Context context) {
		super(context);
		this.context = context;
	}

	public DiandiReaderEditText(Context context, AttributeSet attrs) {
        super(context, attrs); 
        this.context = context;
    }
	

	
	//使用指定的KeyListener
	@Override  
    public boolean getDefaultEditable() {   
        return false;   
    }

	

	//覆写长按弹出的上下文菜单
	@Override
	protected void onCreateContextMenu(ContextMenu menu) {
		
	}

	//重写setText
	@Override
	public void setText(CharSequence text, BufferType type) {
		this.text = text.toString();
		super.setText(null, null);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if(this.text==null||"".equals(this.text))
			return;
		int currentLineCharCounts = 0;
		int lineCounts = 1;
		Paint paint = new Paint();
		paint.setColor(this.getTextColors().getDefaultColor());
		paint.setTextSize(this.getTextSize());
		paint.setTypeface(Typeface.SANS_SERIF);
		//set this property to Anti Aliasing
		paint.setAntiAlias(true);
//		paint.setFlags(Paint.ANTI_ALIAS_FLAG);
		rowCharws = (int)((screenWidth)/this.getTextSize());
		columnChars = (int)(screenHeight/this.getLineHeight());
		//draw the text
		char[] chars = this.text.toCharArray();
		String str ;
		for(int i=0;i<chars.length;i++){
			if(currentLineCharCounts>=rowCharws){
				currentLineCharCounts = 0;
				lineCounts++;
			}
			if(chars[i]=='\n'){
				currentLineCharCounts = 0;
				lineCounts++;
				continue;
			}
			if(chars[i]=='\r'){
				continue;
			}else {
				str = String.valueOf(chars[i]);
			}
			canvas.drawText(str, x+currentLineCharCounts*this.getTextSize(), y+this.getLineHeight()*lineCounts, paint);
			currentLineCharCounts++;
			if(lineCounts>columnChars){
				return;
			}
		}
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		screenWidth = MeasureSpec.getSize(widthMeasureSpec);
		screenHeight = MeasureSpec.getSize(heightMeasureSpec);
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}

	@Override
	public Editable getText() {
//		super.getText();
		Editable editable = new SpannableStringBuilder(this.text);
		return editable;
	} 
	
}
